<?php
/**
 * Created by PhpStorm
 * Author: Rocky
 * DateTime: 2021-11-21 20:13
 */

$config = [
    'host' => '192.168.31.196',
    'port' => 5672,
    'vhost' => 'test_virtual',
    'login' => 'test',
    'password' => '123456'
];

// 连接broker
$connection = new AMQPConnection($config);
if (!$connection->connect()) {
    die('连接失败！');
}

// 创建通道
$channel = new AMQPChannel($connection);
// 创建交换机
$exchange = new AMQPExchange($channel);
// 声明交换机名称
$exchangeName = 'exchange_order';
// 设置交换机名称
$exchange->setName($exchangeName);
// 设置交换机类型
$exchange->setType(AMQP_EX_TYPE_DIRECT);
// 设置交换机属性：持久化
$exchange->setFlags(AMQP_DURABLE);
// 交换机声明
$exchange->declareExchange();

// 创建队列
$queue = new AMQPQueue($channel);
// 声明队列名称
$queueName = 'queue_order';
// 设置队列名称
$queue->setName($queueName);
// 设置队列持久化
$queue->setFlags(AMQP_DURABLE);
// 队列声明
$queue->declareQueue();

// 声明路由键
$routingKey = 'key_order';
// 设置队列绑定交换机和路由键
$queue->bind($exchange->getName(), $routingKey);

// 设置通道每次推送数量
$channel->qos(0, 10);

// 监听队列
echo 'consumer queue starting: ' . PHP_EOL;
while (true) {
    $queue->consume('receiveMessageAndProcess');
}
// 回调方法
function receiveMessageAndProcess($envelope, $queue)
{
    echo $envelope->getBody() . PHP_EOL . PHP_EOL;
//    sleep(1);
    $queue->ack($envelope->getDeliveryTag());
}

$channel->close();
$connection->disconnect();